package com.company.vmpx.api;


import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.company.vmpx.api.cookie.CookieJarImpl;
import com.company.vmpx.api.cookie.store.DBCookieStore;
import com.company.vmpx.tools.AppTools;
import com.dee.components.VnUtils;
import com.dee.components.baserx.BasicParamsInterceptor;
import com.dee.components.baserx.DownloadInterceptor;
import com.dee.components.baserx.DownloadListener;
import com.dee.components.baserx.MyHttpLoggingInterceptor;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者：kkan on 2017/11/30
 * 当前类注释:
 * 使用Retrofit 封装 的网络请求
 * 用例:
 * HttpManager.getOkHttpUrlService() .compose(RxSchedulers.<HttpRespose<Bean>io_main())
 * .subscribe(new RxSubscriber<Bean>(mContext, "加载框信息,不传不显示") {
 * public void _onNext(Bean data) {
 * //处理返回数据,根据需要返回给页面
 * }
 * public void _onError(int code, String message) {
 * //处理异常数据
 * mView.onError(code, message);
 * }
 * });
 */
public class HttpManager {
    //读超时长，单位：秒
    private static final int READ_TIME_OUT = 30;
    //连接时长，单位：秒
    private static final int CONNECT_TIME_OUT = 30;

    private static final int DEFAULT_TIMEOUT = 15;

    private static final String TAG = HttpManager.class.getSimpleName();

    /*服务器跟地址*/
    private static final String BASE_URL = "https://192.168.10.1:8443/";//必须/结尾
    private volatile static HttpManager INSTANCE;

    private OkHttpClient okHttpClient;
    private HttpUrlService httpUrlService;
    private HttpUrlService httpDownloadUrlService;


    /* 获取单例*/
    public static HttpManager getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new HttpManager(BASE_URL);
        }
        return INSTANCE;
    }

    public HttpManager setToken(String token) {
        String oldtoken  = AppTools.getToken();
        if (!token.equals(oldtoken)) {
            INSTANCE = null;
        }
        AppTools.saveToken(token);
        return getInstance();
    }

    //构造方法私有
    private HttpManager(String BaseUrl) {
        //缓存
        Cache cache = getCache();

        //添加公共头和参数
        BasicParamsInterceptor basicParamsInterceptor = getBasicParamsInterceptor(AppTools.getToken());

        //开启Log
        MyHttpLoggingInterceptor logInterceptor = new MyHttpLoggingInterceptor()
                .setLevel(MyHttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(basicParamsInterceptor)
                .addInterceptor(logInterceptor)
                .cookieJar(new CookieJarImpl(new DBCookieStore(VnUtils.getContext())))  //使用数据库保持cookie，如果cookie不过期，则一直有效
                //.cookieJar(new CookieJarImpl(new SPCookieStore(this)))            //使用sp保持cookie，如果cookie不过期，则一直有效
                //.cookieJar(new CookieJarImpl(new MemoryCookieStore()))           //使用内存保持cookie，app退出后，cookie消失
                .cache(cache)
                .build();

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .baseUrl(BaseUrl)
                .build();
        httpUrlService = retrofit.create(HttpUrlService.class);
    }

    /*
     * 请求的拦截处理 添加公共头和参数
     * 请求头和请求参数都增加
     */
    private BasicParamsInterceptor getBasicParamsInterceptor(String token){
        BasicParamsInterceptor.Builder builder = new BasicParamsInterceptor.Builder();
        if (!TextUtils.isEmpty(token)) {
//            builder.addHeaderParams("Cookie", "SESSIONID="+token);//添加公共参数
            builder.addHeaderParams("Authorization", token);//添加公共参数
        }
        //公共请求头
//        builder.addHeaderParams("X-Requested-With", "XMLHttpRequest");//
        builder.addHeaderParams("Content-Type", "application/json");//
//        builder.addHeaderParams("Accept", "application/json");//
        return builder.build();
    }

    /*
     * 缓存
     */
    private Cache getCache(){
        //缓存
        File cacheFile = new File(VnUtils.getContext().getCacheDir(), "cache");
        return new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
    }

    /**
     * HttpUrlService
     */
    public HttpUrlService getOkHttpUrlService() {
        return getInstance().httpUrlService;
    }

    private OkHttpClient getOkHttpClient() {
        return getInstance().okHttpClient;
    }

    /**
     * HttpUrlService
     */
    public HttpUrlService getImageUrlService() {
        Retrofit retrofit = new Retrofit.Builder()
                .client(getOkHttpClient())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();
        httpDownloadUrlService = retrofit.create(HttpUrlService.class);
        return getInstance().httpDownloadUrlService;
    }
    /**
     * HttpUrlService
     */
    public HttpUrlService getDownloadUrlService(String BaseUrl, DownloadListener downloadListener) {

        DownloadInterceptor mInterceptor = new DownloadInterceptor(downloadListener);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(mInterceptor)
                .build();

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .baseUrl(BaseUrl)
                .build();
        httpDownloadUrlService = retrofit.create(HttpUrlService.class);
        return getInstance().httpDownloadUrlService;
    }
}